package com.snow.useviewdemo.qiniuplay;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;


import com.pili.pldroid.player.PLMediaPlayer;
import com.snow.common.tool.utils.ImageUtil;
import com.snow.useviewdemo.R;
import com.snow.useviewdemo.qiniuplay.video.PlayFileUtils;
import com.snow.useviewdemo.qiniuplay.video.PlayOnceVideoManager;
import com.snow.useviewdemo.util.OnAntiDoubleClickListener;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * author : zyt
 * e-mail : 632105276@qq.com
 * date   : 2019-06-10
 * desc   :播放控件View
 */
public class QPLBaseQPLVideoPlayView extends QPLVideoGestureRelativeLayout
        implements QPLVideoGestureRelativeLayout.VideoGestureListener {

    @BindView(R.id.textureView)
    TextureView textureView;
    @BindView(R.id.mask_view)
    View maskView;//遮层
    @BindView(R.id.iv_cover)
    ImageView ivCover;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;
    @BindView(R.id.val_view)
    QPLVideoAttributeLayout valView;
    @BindView(R.id.iv_replay)
    LinearLayout ivReplay;
    @BindView(R.id.replay_rl)
    RelativeLayout replayRl;
    @BindView(R.id.rl_root)
    RelativeLayout rlRoot;
    private Context mContext;

    //声音管理
    private AudioManager systemAudioManager;
    //亮度管理
    private BrightnessHelper mBrightnessHelper;
    private int maxVolume = 0;
    private int oldVolume = 0;
    private int newProgress = 0, oldProgress = 0;
    private float brightness = 1;
    private int movePosition = 0;
    private Window mWindow;
    private WindowManager.LayoutParams mLayoutParams;
    private PLMediaPlayer aliyunVodPlayer;

    public QPLBaseQPLVideoPlayView(Context context) {
        this(context, null);
    }

    public QPLBaseQPLVideoPlayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initView();
        initListener();
    }

    private void initView() {
        LayoutInflater.from(mContext).inflate(R.layout.qpl_view_base_video_play_layout, this);
        ButterKnife.bind(this, this);

        aliyunVodPlayer = PlayOnceVideoManager.init().getAliyunVodPlayer();
        //设置视频比例为填满
//        aliyunVodPlayer.setVideoScalingMode(IAliyunVodPlayer.VideoScalingMode.VIDEO_SCALING_MODE_SCALE_TO_FIT);
        //初始化获取音量属性
        systemAudioManager = (AudioManager) mContext.getSystemService(Service.AUDIO_SERVICE);
        maxVolume = systemAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        //初始化亮度调节
        mBrightnessHelper = new BrightnessHelper(mContext);
        //下面这是设置当前APP亮度的方法配置
        mWindow = ((Activity) mContext).getWindow();
        mLayoutParams = mWindow.getAttributes();
        brightness = mLayoutParams.screenBrightness;

        ivReplay.setOnClickListener(new OnAntiDoubleClickListener() {
            @Override
            public void onAntiDoubleClick(View v) {
                PlayOnceVideoManager.init().rePlay();
                replayRl.setVisibility(GONE);
            }
        });
    }

    /**
     * 显示视频封面
     */
    public void showVideoCover(String VideoCover) {
        rlLoading.setVisibility(VISIBLE);
        ImageUtil.imageLoad(mContext, VideoCover, ivCover);
    }

    /**
     * 隐藏视频封面和加载提示
     */
    public void hindVideoCoverLoading() {
        rlLoading.setVisibility(GONE);
    }

    /**
     * 隐藏再次播放的提示按钮
     */
    public void hindReplayView() {
        replayRl.setVisibility(GONE);
    }

    /**
     * 播放完成显示
     */
    public void playComplementShowView() {
        replayRl.setVisibility(VISIBLE);
    }

    /**
     * 初始化监听
     */
    private void initListener() {
        setVideoGestureListener(this);
        textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                Surface s = new Surface(surface);
                aliyunVodPlayer.setSurface(s);
                Log.e("snowzhao", "=setSurfaceTextureListener=========setSurface(s)=");
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                return true;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {

            }
        });
    }

    public void setSurfaceTexture() {
        aliyunVodPlayer.setSurface(new Surface(textureView.getSurfaceTexture()));
    }

    @Override
    public void onBrightnessGesture(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        dealBrightnes(e1, e2);
    }

    @Override
    public void onVolumeGesture(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        dealVolume(e1, e2);
    }

    @Override
    public void onFF_REWGesture(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        if (!PlayOnceVideoManager.init().isPlaying()) {
            return;
        }
        float offset = e2.getX() - e1.getX();
        //根据移动的正负决定快进还是快退
        if (offset > 0) {
            newProgress = (int) (oldProgress + offset / rlRoot.getWidth() * 100);
            if (newProgress > 100) {
                newProgress = 100;
            }
        } else {
            newProgress = (int) (oldProgress + offset / rlRoot.getWidth() * 100);
            if (newProgress < 0) {
                newProgress = 0;
            }
        }
        int duration = (int) aliyunVodPlayer.getDuration();
        String durationTime = PlayFileUtils.init().formatTime(duration);
        double pro = newProgress / 100.00D;
        movePosition = (int) (duration * pro);
        String moveTime = PlayFileUtils.init().formatTime(movePosition);
        valView.setProgress(newProgress);
        valView.setTvTime(moveTime + "/" + durationTime);
        valView.showPrggressDialog();
    }

    @Override
    public void onSingleTapGesture(MotionEvent e) {
        if (viewListener != null) {
            viewListener.singleTapGesture();
        }
    }

    @Override
    public void onDoubleTapGesture(MotionEvent e) {
        if (viewListener != null) {
            viewListener.doubleTapGesture();
        }
    }

    @Override
    public void onDown(MotionEvent e) {
        if (aliyunVodPlayer.getDuration() > 0) {
            oldProgress = (int) (aliyunVodPlayer.getCurrentPosition() / (aliyunVodPlayer.getDuration() * 1.0f) * 100);
        }
        movePosition = 0;
        oldVolume = systemAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        brightness = mLayoutParams.screenBrightness;
        if (brightness == -1) {
            //一开始是默认亮度的时候，获取系统亮度，计算比例值
            brightness = mBrightnessHelper.getBrightness() / 255f;
        }
    }

    @Override
    public void onEndFF_REW(MotionEvent e) {
        if (newProgress != 0) {
            if (viewListener != null) {
                viewListener.onEndMoveAction(newProgress);
            }
//            sbProgress.setCurrentProgress(newProgress);
        }
        if (aliyunVodPlayer != null && movePosition != 0) {
            aliyunVodPlayer.seekTo(movePosition);
//            mHandler.sendEmptyMessage(3);
        }
    }

    public void setBaseVideoPlayListener(BaseVideoPlayViewListener viewListener) {
        this.viewListener = viewListener;
    }

    private BaseVideoPlayViewListener viewListener;

    public interface BaseVideoPlayViewListener {
        void doubleTapGesture();

        void singleTapGesture();

        void onEndMoveAction(int newProgress);
    }

    /**
     * 处理亮度
     *
     * @param e1
     * @param e2
     */
    private void dealBrightnes(MotionEvent e1, MotionEvent e2) {
        //下面这是设置当前APP亮度的方法
        float newBrightness = (e1.getY() - e2.getY()) / rlRoot.getHeight();
        newBrightness += brightness;

        if (newBrightness < 0) {
            newBrightness = 0;
        } else if (newBrightness > 1) {
            newBrightness = 1;
        }
        mLayoutParams.screenBrightness = newBrightness;
        mWindow.setAttributes(mLayoutParams);
        valView.setProgress((int) (newBrightness * 100));
//        valView.setImageResource(R.mipmap.ic_video_play_brightness);
        valView.show();
    }

    /**
     * 处理音量
     *
     * @param e1
     * @param e2
     */
    private void dealVolume(MotionEvent e1, MotionEvent e2) {
        int value = rlRoot.getHeight() / maxVolume;
        int newVolume = (int) ((e1.getY() - e2.getY()) / value + oldVolume);
        systemAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newVolume, AudioManager.FLAG_PLAY_SOUND);
        //要强行转Float类型才能算出小数点，不然结果一直为0
        int volumeProgress = (int) (newVolume / Float.valueOf(maxVolume) * 100);
//        if (volumeProgress >= 50) {
//            valView.setImageResource(R.mipmap.icon_videoplay_volume_higher);
//        } else if (volumeProgress > 0) {
//            valView.setImageResource(R.mipmap.icon_videoplay_volume_lower);
//        } else {
//            valView.setImageResource(R.mipmap.icon_videoplay_volume_off);
//        }
        valView.setProgress(volumeProgress);
        valView.show();
    }
}
